<template>
  <!-- 方案比对页面容器 -->
  <div class="plan-comparison-container">
    <el-container class="main-container">
      <!-- 左侧：方案列表 -->
      <el-aside class="plan-list-aside" :style="{ width: asideWidth + 'px' }">
        <div class="aside-header">
          <span class="panel-title">
            <el-icon style="margin-right: 8px;"><Document /></el-icon>
            方案列表
          </span>
          <el-tag type="info" size="small">共{{ constraints.length }}个方案</el-tag>
        </div>
        <el-divider class="custom-divider" />
        
        <div class="aside-content">
          <!-- 约束列表 -->
          <div 
            v-for="(constraint, index) in constraints" 
            :key="constraint.id" 
            class="constraint-item"
            :class="{ active: selectedConstraintIndex === index }"
          >
            <div class="constraint-info" @click="selectConstraint(index, constraint)">
              <div class="constraint-header">
                <el-checkbox 
                  v-model="constraint.checked" 
                  @click.stop 
                  @change="handleConstraintCheckChange(constraint)"
                  class="constraint-checkbox"
                />
                <el-icon class="constraint-icon" :color="getConstraintColor(index)">
                  <Document />
                </el-icon>
                <span class="constraint-title">{{ constraint.title }}</span>
              </div>
              <div v-if="selectedConstraintIndex === index && constraintDetail" class="constraint-meta">
                <el-tag size="small" type="success">已查看</el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部按钮区域 -->
        <div class="aside-footer">
          <el-button 
            type="primary" 
            class="comparison-button"
            :disabled="checkedConstraints.length === 0"
            @click="openComparisonDialog"
          >
            <el-icon><TrendCharts /></el-icon>
            方案比对 ({{ checkedConstraints.length }})
          </el-button>
        </div>
      </el-aside>

      <!-- 分隔条 -->
      <div class="resizer" @mousedown="startResize"></div>

      <!-- 右侧：方案详情 -->
      <el-main class="plan-details-main">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <el-icon class="is-loading" :size="40">
            <Loading />
          </el-icon>
          <p>{{ loadingText }}</p>
        </div>

        <!-- 空状态 -->
        <div v-else-if="!selectedConstraintItem?.id" class="empty-state">
          <el-icon :size="64" color="#c0c4cc">
            <Document />
          </el-icon>
          <h3>方案详情</h3>
          <p>请从左侧选择一个方案查看计划详情</p>
        </div>

        <!-- 方案详情内容 -->
        <div v-else class="plan-content">
          <!-- 方案详情头部 -->
          <div class="plan-header">
            <span class="panel-title">
              <el-icon style="margin-right: 8px;"><Document /></el-icon>
              {{ selectedConstraintItem.title }}
            </span>
          </div>
          <el-divider class="custom-divider" />

          <!-- 1. KPI 指标（放在最上面） -->
          <div class="section-block">
            <div class="section-header">
              <span class="section-title">
                <el-icon style="margin-right: 4px;"><DataAnalysis /></el-icon>
                KPI 指标总览
              </span>
            </div>
            
            <!-- 维度切换区域 -->
            <div class="dimension-switcher">
              <div class="switcher-header">
                <h3>排程数据分析</h3>
                <p>基于 APS 算法的设备级排程结果</p>
              </div>
              <div class="dimension-tabs">
                <div 
                  :class="['dimension-tab', { active: currentDimension === 'order' }]"
                  @click="switchDimension('order')"
                >
                  <el-icon class="tab-icon"><Tickets /></el-icon>
                  <div class="tab-content">
                    <h4>订单维度</h4>
                    <p>查看订单排程情况</p>
                  </div>
                </div>
                <div 
                  :class="['dimension-tab', { active: currentDimension === 'device' }]"
                  @click="switchDimension('device')"
                >
                  <el-icon class="tab-icon"><Monitor /></el-icon>
                  <div class="tab-content">
                    <h4>设备维度</h4>
                    <p>查看设备利用情况</p>
                  </div>
                </div>
              </div>
            </div>

            <!-- 订单维度组件 -->
            <OrderDimension 
              v-if="currentDimension === 'order'"
              :constraint-id="selectedConstraintItem?.id"
              @metric-detail="showMetricDetail"
            />

            <!-- 设备维度组件 -->
            <DeviceDimension 
              v-if="currentDimension === 'device'"
              :constraint-id="selectedConstraintItem?.id"
              @metric-detail="showMetricDetail"
            />
          </div>

          <!-- 2. Tab 切换：计划详情 和 排程甘特图 -->
          <div class="section-block">
            <el-tabs v-model="activeTab" class="plan-tabs">
              <el-tab-pane label="计划详情" name="detail">
                <template #label>
                  <span class="tab-label">
                    <el-icon style="margin-right: 4px;"><Document /></el-icon>
                    计划详情
                    <el-tag size="small" type="info" style="margin-left: 8px;" v-if="planDetailData && planDetailData.length">
                      {{ planDetailData.length }}
                    </el-tag>
                  </span>
                </template>
                <div class="tab-content">
                  <PlanDetailTable 
                    v-if="planDetailData && planDetailData.length > 0"
                    :table-data="planDetailData"
                    :constraint-id="selectedConstraintItem.id"
                  />
                  <el-empty v-else description="暂无计划详情数据" :image-size="120" />
                </div>
              </el-tab-pane>
              <el-tab-pane label="排程甘特图" name="gantt">
                <template #label>
                  <span class="tab-label">
                    <el-icon style="margin-right: 4px;"><TrendCharts /></el-icon>
                    排程甘特图
                  </span>
                </template>
                <div class="tab-content">
                  <GanttChart 
                    v-if="ganttData && ganttData.length > 0"
                    :chart-data="ganttData"
                    :constraint-id="selectedConstraintItem.id"
                    :height="350"
                  />
                  <el-empty v-else description="暂无甘特图数据" :image-size="120" />
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </el-main>
    </el-container>

    <!-- 方案比对对话框 -->
    <PlanComparisonDialog
      v-model="comparisonDialogVisible"
      :selected-plans="checkedConstraints"
      :comparison-metrics="comparisonMetrics"
      @remove-plan="handleRemovePlan"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Document, 
  Loading, 
  TrendCharts, 
  DataAnalysis,
  Tickets,
  Monitor
} from '@element-plus/icons-vue'
import GanttChart from '@/components/planComparison/GanttChart.vue'
import PlanDetailTable from '@/components/planComparison/PlanDetailTable.vue'
import PlanComparisonDialog from '@/components/planComparison/PlanComparisonDialog.vue'
import OrderDimension from '@/components/planComparison/OrderDimension.vue'
import DeviceDimension from '@/components/planComparison/DeviceDimension.vue'
import { planComparisonApi } from '@/api/planComparison'

export default {
  name: 'PlanComparison',
  components: {
    GanttChart,
    PlanDetailTable,
    PlanComparisonDialog,
    OrderDimension,
    DeviceDimension,
    Document,
    Loading,
    TrendCharts,
    DataAnalysis,
    Tickets,
    Monitor
  },
  setup() {
    const route = useRoute()

    // ============== 1. 状态管理 ==============
    
    // 约束列表
    const constraints = ref([])
    
    // 当前选中的约束索引
    const selectedConstraintIndex = ref(null)
    
    // 当前选中的约束对象
    const selectedConstraintItem = ref({})
    
    // 约束详情数据
    const constraintDetail = ref(null)
    
    // 加载状态
    const loading = ref(false)
    const loadingText = ref('加载中...')
    
    // 甘特图数据
    const ganttData = ref([])
    
    // 计划详情数据
    const planDetailData = ref([])
    
    // 所有方案的指标数据（用于比对）
    const allPlansMetrics = ref([])
    
    // 方案比对对话框显示状态
    const comparisonDialogVisible = ref(false)
    
    // 当前活动的Tab（计划详情/甘特图）
    const activeTab = ref('detail')
    
    // 当前维度：order/device，默认加载订单维度
    const currentDimension = ref('order')
    
    // 勾选的约束（用于比对分析）
    const checkedConstraints = computed(() => {
      return constraints.value.filter(c => c.checked)
    })
    
    // 比对分析的指标数据（根据勾选的约束筛选）
    const comparisonMetrics = computed(() => {
      if (!allPlansMetrics.value || allPlansMetrics.value.length === 0) {
        return []
      }
      const checkedIds = checkedConstraints.value.map(c => c.id)
      return allPlansMetrics.value.filter(m => checkedIds.includes(m.constraintId))
    })

    // 左侧面板宽度
    const asideWidth = ref(300)
    const isResizing = ref(false)
    const lastClientX = ref(0)

    // ============== 2. 初始化方法 ==============

    /**
     * 初始化约束列表
     */
    const initializeConstraints = async () => {
      try {
        loading.value = true
        loadingText.value = '正在加载约束列表...'

        // 1. 获取路由参数中的constraintIds
        const constraintIds = route.query.constraintIds
        if (!constraintIds) {
          ElMessage.warning('缺少约束配置ID参数')
          loading.value = false
          return
        }

        console.log('📋 路由参数 constraintIds:', constraintIds)

        // 2. 调用后端接口获取约束列表
        const res = await planComparisonApi.queryConstraintList(constraintIds)
        
        if (res && res.success && res.data) {
          constraints.value = res.data.map(item => ({
            id: item.baseParameters?.constraintInfo?.id || item.id,
            title: item.baseParameters?.constraintInfo?.title || '未命名方案',
            checked: false, // 默认不勾选
            fullData: item // 保存完整数据
          }))
        }

        console.log('📋 加载约束列表:', {
          count: constraints.value.length,
          constraints: constraints.value
        })

        // 3. 自动选择第一个约束并加载详情
        if (constraints.value.length > 0) {
          const firstConstraint = constraints.value[0]
          await selectConstraint(0, firstConstraint)
        }
      } catch (error) {
        console.error('❌ 加载约束列表失败:', error)
        ElMessage.error('加载约束列表失败')
      } finally {
        loading.value = false
      }
    }

    /**
     * 选择约束配置
     */
    const selectConstraint = async (index, item) => {
      console.log('🔄 切换约束:', {
        index,
        constraintId: item?.id,
        constraintTitle: item?.title
      })

      if (!item?.id) {
        ElMessage.warning('约束数据无效')
        return
      }

      // 避免重复选择
      if (selectedConstraintIndex.value === index && 
          selectedConstraintItem.value?.id === item.id) {
        return
      }

      try {
        loading.value = true
        loadingText.value = `正在加载方案【${item.title}】...`

        // 更新选中状态
        selectedConstraintIndex.value = index
        selectedConstraintItem.value = { ...item }

        // 加载约束详情和排程数据
        await loadConstraintDetail(item.id)
        await loadPlanData(item.id)
      } catch (error) {
        console.error('❌ 加载方案数据失败:', error)
        ElMessage.error('加载方案数据失败')
      } finally {
        loading.value = false
      }
    }

    /**
     * 加载约束详情
     */
    const loadConstraintDetail = async (constraintId) => {
      try {
        // TODO: 后续如果需要加载约束详情，可以调用对应的API
        // const res = await constraintApi.getById(constraintId)
        constraintDetail.value = { id: constraintId }
        console.log('📄 加载约束详情成功:', constraintId)
      } catch (error) {
        console.error('❌ 加载约束详情失败:', error)
      }
    }

    /**
     * 加载排程计划数据
     */
    const loadPlanData = async (constraintId) => {
      try {
        // 调用后端接口查询计划详情列表（分页）
        const pageQuery = {
          pageSize: 1000, // 暂时设置一个较大的值，后续可以优化为真正的分页
          pageNum: 1,
          condition: {
            constraintId: constraintId
          }
        }
        
        const detailRes = await planComparisonApi.queryPlanListByConfigId(pageQuery)

        // 设置详情表格数据
        if (detailRes && detailRes.success && detailRes.data) {
          console.log('📋 加载计划详情数据:', detailRes.data)
          planDetailData.value = detailRes.data.rows || []
        }

        // TODO: 甘特图数据接口
        ganttData.value = []
      } catch (error) {
        console.error('❌ 加载排程数据失败:', error)
        ganttData.value = []
        planDetailData.value = []
      }
    }


    // ============== 3. 方案比对相关 ==============

    /**
     * 打开方案比对对话框
     */
    const openComparisonDialog = () => {
      if (checkedConstraints.value.length === 0) {
        ElMessage.warning('请至少勾选一个方案进行对比')
        return
      }
      
      console.log('📊 打开方案比对对话框:', {
        selectedCount: checkedConstraints.value.length,
        selectedPlans: checkedConstraints.value.map(c => ({ id: c.id, title: c.title }))
      })
      
      comparisonDialogVisible.value = true
    }

    /**
     * 从比对中移除方案
     */
    const handleRemovePlan = (planId) => {
      const constraint = constraints.value.find(c => c.id === planId)
      if (constraint) {
        constraint.checked = false
      }
    }

    /**
     * 处理约束勾选变化
     */
    const handleConstraintCheckChange = (constraint) => {
      console.log('✅ 勾选约束变化:', {
        constraintId: constraint.id,
        constraintTitle: constraint.title,
        checked: constraint.checked,
        checkedCount: checkedConstraints.value.length,
        timestamp: new Date().toISOString()
      })
    }

    // ============== 4. 工具方法 ==============

    /**
     * 获取约束颜色（使用主题色）
     */
    const getConstraintColor = (index) => {
      return '#714B67'
    }
    
    /**
     * 显示指标详情（hover效果或弹窗）
     */
    const showMetricDetail = (metricType) => {
      console.log('显示指标详情:', metricType)
      // TODO: 实现指标详情展示
    }
    
    /**
     * 切换维度
     */
    const switchDimension = (dimension) => {
      currentDimension.value = dimension
    }

    // ============== 5. 拖拽调整面板宽度 ==============

    const startResize = (e) => {
      isResizing.value = true
      lastClientX.value = e.clientX
      document.addEventListener('mousemove', handleResizing)
      document.addEventListener('mouseup', stopResize)
    }

    const handleResizing = (e) => {
      if (!isResizing.value) return
      const deltaX = e.clientX - lastClientX.value
      asideWidth.value = Math.max(250, Math.min(500, asideWidth.value + deltaX))
      lastClientX.value = e.clientX
    }

    const stopResize = () => {
      isResizing.value = false
      document.removeEventListener('mousemove', handleResizing)
      document.removeEventListener('mouseup', stopResize)
    }

    // ============== 6. 生命周期 ==============

    onMounted(() => {
      initializeConstraints()
    })

    // 监听路由变化
    watch(() => route.query.constraintIds, () => {
      initializeConstraints()
    })

    return {
      // 状态
      constraints,
      selectedConstraintIndex,
      selectedConstraintItem,
      constraintDetail,
      loading,
      loadingText,
      ganttData,
      planDetailData,
      allPlansMetrics,
      checkedConstraints,
      comparisonMetrics,
      comparisonDialogVisible,
      asideWidth,
      activeTab,
      currentDimension,
      // 方法
      selectConstraint,
      openComparisonDialog,
      handleRemovePlan,
      getConstraintColor,
      handleConstraintCheckChange,
      startResize,
      showMetricDetail,
      switchDimension
    }
  }
}
</script>

<style scoped>
/* 整体容器 */
.plan-comparison-container {
  height: 100vh;
  background-color: #f5f7fa;
  padding: 0.8%;
}

.main-container {
  height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 左侧方案列表 */
.plan-list-aside {
  display: flex;
  flex-direction: column;
  background: white;
  border-right: 1px solid #e4e7ed;
  height: 100%;
}

.aside-header {
  padding: 1.5%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.panel-title {
  color: #714B67;
  font-size: 1.6vw;
  font-weight: 700;
  font-family: "Microsoft YaHei", "Noto Sans SC", sans-serif;
  display: flex;
  align-items: center;
}

.aside-content {
  flex: 1;
  overflow-y: auto;
  padding: 0 1.2%;
}

.aside-footer {
  padding: 1.2%;
  border-top: 1px solid #e4e7ed;
  flex-shrink: 0;
}

.comparison-button {
  width: 100%;
  background-color: #714B67;
  border-color: #714B67;
  font-size: 1vw;
  height: 3.2vh;
}

/* 自定义分隔线 */
.custom-divider {
  margin: 10px 0;
  border-style: dotted;
}

/* 约束列表项样式 */
.constraint-item {
  margin-bottom: 10px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.constraint-item:hover {
  background: #ecf5ff;
  border-color: #714B67;
}

.constraint-item.active {
  background: #ecf5ff;
  border-color: #714B67;
  box-shadow: 0 2px 8px rgba(113, 75, 103, 0.2);
}

.constraint-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  cursor: pointer;
}

.constraint-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.constraint-checkbox {
  flex-shrink: 0;
}

.constraint-icon {
  flex-shrink: 0;
}

.constraint-title {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.constraint-meta {
  display: flex;
  justify-content: flex-end;
  margin-left: 24px;
}

/* 分隔条样式 */
.resizer {
  width: 4px;
  cursor: col-resize;
  background-color: #dcdfe6;
  transition: background-color 0.3s;
  flex-shrink: 0;
}

.resizer:hover {
  background-color: #714B67;
}

/* 右侧方案详情 */
.plan-details-main {
  flex: 1;
  padding: 1.5%;
  overflow-y: auto;
  background: white;
  height: 100%;
}

.plan-content {
  width: 100%;
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

/* 区块样式 */
.section-block {
  margin-bottom: 1.8%;
}

.section-block:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.2%;
  padding-bottom: 0.8%;
  border-bottom: 1px solid #e4e7ed;
}

.section-title {
  font-weight: 600;
  font-size: 1.4vw;
  color: #714B67;
  display: flex;
  align-items: center;
}

.section-actions {
  display: flex;
  gap: 8px;
}

/* 按钮样式 */
.idoo-details-add {
  background-color: #714B67;
  border-color: #714B67;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #909399;
}

.loading-state p {
  margin-top: 15px;
  font-size: 14px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #909399;
}

.empty-state h3 {
  margin: 20px 0 10px;
  color: #714B67;
  font-size: 22px;
  font-weight: 600;
}

.empty-state p {
  font-size: 14px;
}

/* 维度切换器 */
.dimension-switcher {
  background: linear-gradient(135deg, #714B67 0%, #8B6B7F 100%);
  border-radius: 12px;
  padding: 1.8%;
  margin-bottom: 1.5%;
  color: white;
  position: relative;
  overflow: hidden;
}

.dimension-switcher::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
  animation: pulse 4s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(0.8); opacity: 0.5; }
  50% { transform: scale(1.2); opacity: 0.8; }
}

.switcher-header {
  text-align: center;
  margin-bottom: 1.5%;
  position: relative;
  z-index: 1;
}

.switcher-header h3 {
  margin: 0 0 0.6%;
  font-size: 1.6vw;
  font-weight: 600;
  color: white;
}

.switcher-header p {
  margin: 0;
  font-size: 1vw;
  opacity: 0.9;
}

.dimension-tabs {
  display: flex;
  gap: 1.5%;
  position: relative;
  z-index: 1;
}

.dimension-tab {
  flex: 1;
  background: rgba(255, 255, 255, 0.1);
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  padding: 1.5%;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 1.2%;
  backdrop-filter: blur(10px);
}

.dimension-tab:hover {
  background: rgba(255, 255, 255, 0.15);
  border-color: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.dimension-tab.active {
  background: rgba(255, 255, 255, 0.2);
  border-color: rgba(255, 255, 255, 0.4);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}

.tab-icon {
  font-size: 3.2vw;
  opacity: 0.8;
}

.tab-content h4 {
  margin: 0 0 0.3%;
  font-size: 1.25vw;
  font-weight: 600;
}

.tab-content p {
  margin: 0;
  font-size: 0.9vw;
  opacity: 0.8;
}

.tab-badge {
  margin-left: auto;
  text-align: center;
}

.tab-badge span {
  display: block;
  font-size: 28px;
  font-weight: 700;
}

.tab-badge small {
  font-size: 12px;
  opacity: 0.8;
}


/* Tab 样式 */
.plan-tabs {
  width: 100%;
}

.plan-tabs :deep(.el-tabs__header) {
  margin-bottom: 1.5%;
  border-bottom: 2px solid #e4e7ed;
}

.plan-tabs :deep(.el-tabs__item) {
  padding: 0 1.5%;
  height: 3.5vh;
  line-height: 3.5vh;
  font-size: 1.05vw;
  font-weight: 500;
  color: #606266;
}

.plan-tabs :deep(.el-tabs__item.is-active) {
  color: #714B67;
  border-bottom-color: #714B67;
}

.plan-tabs :deep(.el-tabs__item:hover) {
  color: #714B67;
}

.plan-tabs :deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.tab-label {
  display: flex;
  align-items: center;
  white-space: nowrap;
}

.tab-content {
  min-height: 15vh;
}

/* 响应式布局 - 适配不同分辨率 */
@media screen and (min-width: 2560px) {
  .section-title {
    font-size: 1.2vw;
  }
  
  .switcher-header h3 {
    font-size: 1.4vw;
  }
  
  .tab-icon {
    font-size: 2.8vw;
  }
}

@media screen and (max-width: 1920px) and (min-width: 1921px) {
  .section-title {
    font-size: 1.3vw;
  }
}

@media screen and (max-width: 1920px) {
  .section-title {
    font-size: 1.5vw;
  }
  
  .switcher-header h3 {
    font-size: 1.7vw;
  }
  
  .tab-icon {
    font-size: 3.4vw;
  }
}

@media screen and (max-width: 1440px) {
  .section-title {
    font-size: 1.6vw;
  }
  
  .switcher-header h3 {
    font-size: 1.8vw;
  }
  
  .tab-icon {
    font-size: 3.6vw;
  }
}

@media screen and (max-width: 1080px) {
  .section-title {
    font-size: 1.8vw;
  }
  
  .switcher-header h3 {
    font-size: 2vw;
  }
  
  .tab-icon {
    font-size: 4vw;
  }
  
  .dimension-switcher {
    padding: 1.5%;
  }
  
  .dimension-tab {
    padding: 1.2%;
  }
}
</style>

